import axios from 'axios';
import store from '@/store';

let baseUrl = 'http://localhost:80/';

const request = axios.create({
    baseURL: baseUrl,
    timeout: 3000,
    headers: {
        'Content-Type': 'application/json',
    },
});

// 请求拦截器,请求后端接口之前添加一个拦截器
request.interceptors.request.use(
    function (config)  {
        config.headers.token = store.getters.GET_TOKEN;
        return config;
    },
    function (error)  {
        return Promise.reject(error);
    }
);

// 响应拦截器 (这暂时没做处理)
request.interceptors.response.use(
    function (response) {
        return response;
    },
    function (error) {
        return Promise.reject(error);
    }
);

// get请求
export function get(url,params = {}){
     return new Promise( (resolve,reject) => {
        request({
            url,
            method: 'get',
            params: params
        }).then(res => {
            resolve(res.data);
        }).catch(err => {
            reject(err);
        })

     });
}

// post请求
export function post(url,params = {}){
    return new Promise( (resolve,reject) => {
        request({
            url,
            method: 'post',
            data: params
        }).then(res => {
            resolve(res.data);
        }).catch(err => {
            reject(err);
        })

    });
}

// 文件上传
export function fileUpload(url,params = {}){
    return new Promise( (resolve,reject) => {
        request({
            url,
            method: 'post',
            params: params,
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then(res => {
            resolve(res.data);
        }).catch(err => {
            reject(err);
        })

    });
}


// 获取baseurl
export function getBaseUrl() {
    return baseUrl;
}

// 导出所有封装的方法
export default {
    get,
    post,
    fileUpload,
    getBaseUrl
};
